package com.itheima.service.impl;

import com.itheima.common.AuthThreadLocal;

import com.itheima.utils.SnowflakeUtils;
import com.itheima.entity.ShoppingCart;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.service.ShoppingCartService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author HeiMa-sw
 * @Description //TODO 17210
 * @Date 21:00 2022/6/9
 **/
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private SnowflakeUtils snowflakeUtils;

    @Override
    public ShoppingCart saveOne(ShoppingCart shoppingCart) {
        shoppingCart.setId(String.valueOf(snowflakeUtils.snowflakeId()));
        String userId = AuthThreadLocal.getAuth();
        shoppingCart.setUserId(userId);
        shoppingCart.setCreateTime(LocalDateTime.now());
        ShoppingCart shoppingCartCopy = shoppingCartMapper.seleteByName(shoppingCart.getName());
        if (shoppingCartCopy == null) {
            shoppingCart.setNumber(1);
            shoppingCartCopy = shoppingCart;
            shoppingCartMapper.insertOne(shoppingCartCopy);
        } else {
            shoppingCartCopy.setNumber(shoppingCartCopy.getNumber() + 1);
            shoppingCartMapper.updateOne(shoppingCartCopy);
        }
        return shoppingCartCopy;
    }

    @Override
    public int removeOne(final String dishId, final String setmealId) {
        if (setmealId == null) {
            ShoppingCart byDishId = shoppingCartMapper.selectByDishId(dishId);
            int number = byDishId.getNumber();
            if (number > 1) {
                byDishId.setNumber(number - 1);
                return shoppingCartMapper.updateOne(byDishId);
            } else {
                return shoppingCartMapper.deleteById(dishId, setmealId);
            }
        } else {
            ShoppingCart bysetmealId = shoppingCartMapper.selectBysetmealId(setmealId);
            int number = bysetmealId.getNumber();
            if (number > 1) {
                bysetmealId.setNumber(number - 1);
                return shoppingCartMapper.updateOne(bysetmealId);
            } else {
                return shoppingCartMapper.deleteById(dishId, setmealId);
            }
        }
    }

    @Override
    public List<ShoppingCart> getList() {
        return shoppingCartMapper.seleteList();
    }

    @Override
    public void cleanAll() {
        shoppingCartMapper.deleteAll();
    }
}
